<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>录像回放 - MediaMTX视频监控系统</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/all.min.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/flatpickr.min.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/date.css') }}">
    <style>
:root {
            --primary-color: #4e54c8;
            --primary-light: #8f94fb;
            --secondary-color: #27ae60;
            --secondary-light: #2ecc71;
            --danger-color: #e74c3c;
            --text-color: #ffffff;
            --text-light: #a0d2eb;
            --bg-dark: #0a192f;
            --bg-darker: #071120;
            --bg-gradient: linear-gradient(135deg, #1a2a6c, #2c3e50);
            --shadow: 0 10px 30px rgba(0, 0, 0, 0.4);
            --border-radius: 15px;
            --transition: all 0.3s ease;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        body {
            background: var(--bg-gradient);
            color: var(--text-color);
            min-height: 100vh;
            line-height: 1.6;
        }

        .container {
            max-width: 1800px;
            max-height: 90vh;
            margin: 0 auto;
            padding: 20px;
        }

        .dashboard {
            display: grid;
            grid-template-columns: 1fr 400px;
            gap: 25px;
            margin-bottom: 30px;
        }

        .video-container {
            background: rgba(0, 15, 30, 0.8);
            border-radius: var(--border-radius);
            overflow: hidden;
            box-shadow: var(--shadow);
            position: relative;
            display: flex;
            flex-direction: column;
        }

        .video-wrapper {
            position: relative;
            width: 100%;
            padding-top: 56.25%;
            /* 16:9 宽高比 */
            background: #000;
        }

        .video-player {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            outline: none;
        }

        .video-controls {
            padding: 15px;
            background: rgba(0, 20, 40, 0.9);
            display: flex;
            justify-content: center;
            gap: 15px;
            flex-wrap: wrap;
        }

        .control-btn {
            background: var(--primary-color);
            color: white;
            border: none;
            padding: 10px 18px;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 600;
            transition: var(--transition);
            display: flex;
            align-items: center;
            gap: 8px;
            min-width: 100px;
            justify-content: center;
        }

        .control-btn:hover:not(:disabled) {
            background: var(--primary-light);
            transform: translateY(-2px);
        }

        .control-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }

        .btn-success {
            background: var(--secondary-color);
        }

        .btn-success:hover:not(:disabled) {
            background: var(--secondary-light);
        }

        .btn-danger {
            background: var(--danger-color);
        }

        .btn-danger:hover {
            background: #c0392b;
        }

        .panel {
            background: rgba(0, 15, 30, 0.8);
            border-radius: var(--border-radius);
            padding: 25px;
            box-shadow: var(--shadow);
            height: 90vh;
            display: flex;
            flex-direction: column;
            overflow-x: hidden;
            overflow-y: auto;
        }

        .panel-title {
            font-size: 1.4rem;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid var(--primary-color);
            color: var(--primary-light);
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            color: var(--text-light);
            font-weight: 500;
        }

        select,
        input {
            width: 100%;
            padding: 12px;
            border-radius: 8px;
            border: 1px solid var(--primary-color);
            background: rgba(0, 20, 40, 0.7);
            color: white;
            font-size: 1rem;
            transition: var(--transition);
        }

        input[type="datetime-local"] {
            padding: 10px 8px 10px 8px;

        }

        select:focus,
        input:focus {
            outline: none;
            border-color: var(--primary-light);
            box-shadow: 0 0 0 2px rgba(78, 84, 200, 0.3);
        }

        .time-range-container {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
        }

        .time-range-item {
            display: flex;
            flex-direction: column;
        }

        .video-list {
            margin-top: 20px;
            flex-grow: 1;
            overflow-y: auto;
            padding-right: 10px;
        }

        ::-webkit-scrollbar {
            width: 8px;
        }

        ::-webkit-scrollbar-track {
            background: rgba(0, 0, 0, 0.2);
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb {
            background: var(--primary-color);
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: var(--primary-light);
        }

        .video-item {
            background: rgba(0, 25, 50, 0.7);
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
            cursor: pointer;
            transition: var(--transition);
            border: 2px solid transparent;
        }

        .video-item:hover {
            border-color: var(--primary-color);
            transform: translateY(-3px);
        }

        .video-item.active {
            border-color: var(--secondary-color);
            background: rgba(0, 40, 20, 0.7);
        }

        .video-item-title {
            font-size: 1.1rem;
            margin-bottom: 5px;
            display: flex;
            align-items: center;
            gap: 10px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .video-item-info {
            color: var(--text-light);
            font-size: 0.9rem;
            margin-top: 8px;
            display: flex;
            justify-content: space-between;
        }

        .loading-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.8);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            z-index: 10;
            color: white;
        }

        .spinner {
            width: 40px;
            height: 40px;
            border: 4px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: var(--primary-color);
            animation: spin 1s ease-in-out infinite;
            margin-bottom: 15px;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }

        .error-box {
            background: rgba(231, 76, 60, 0.2);
            border: 1px solid var(--danger-color);
            border-radius: 10px;
            padding: 20px;
            margin-top: 20px;
            display: none;
        }

        .error-title {
            color: var(--danger-color);
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 1.2rem;
        }

        .error-message {
            font-family: monospace;
            background: rgba(0, 0, 0, 0.3);
            padding: 15px;
            border-radius: 8px;
            overflow-x: auto;
            font-size: 0.95rem;
        }

        .speed-indicator {
            background: rgba(0, 0, 0, 0.5);
            color: white;
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.8rem;
            position: absolute;
            top: 10px;
            right: 10px;
            z-index: 5;
            display: none;
        }

        .empty-state {
            text-align: center;
            color: var(--text-light);
            padding: 40px 20px;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 15px;
        }

        .empty-state i {
            font-size: 2rem;
            opacity: 0.7;
        }

        footer {
            text-align: center;
            margin-top: 40px;
            padding: 25px;
            color: var(--text-light);
            font-size: 0.95rem;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
        }

        /* 响应式设计 */
        @media (max-width: 1200px) {
            .dashboard {
                grid-template-columns: 1fr;
            }

            .video-wrapper {
                padding-top: 56.25%;
                /* 保持16:9比例 */
            }
        }

        @media (max-width: 768px) {
            .container {
                padding: 10px;
            }

            .video-controls {
                flex-direction: row;
                flex-wrap: wrap;
                gap: 10px;
            }

            .control-btn {
                padding: 8px 12px;
                min-width: auto;
                flex-grow: 1;
            }

            .time-range-container {
                grid-template-columns: 1fr;
            }

            .panel {
                padding: 15px;
            }
        }

        @media (max-width: 480px) {
            .video-controls {
                gap: 5px;
            }

            .control-btn {
                font-size: 0.9rem;
                padding: 6px 8px;
            }

            .control-btn i {
                display: none;
            }
        }
        .flatpickr-time {
            display: block !important; /* 强制显示时间部分 */
        }

        .breadcrumb {
            font-size: 14px;
            margin-bottom: 10px;
            color: #666;
        }

        .breadcrumb a {
            color: #4a6fa5;
            text-decoration: none;
        }

        .breadcrumb a:hover {
            text-decoration: underline;
        }

        .breadcrumb .separator {
            margin: 0 5px;
            color: #999;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <div class="breadcrumb">
            <a href="/index">主页</a>
            <span class="separator">/</span>
            <span>实时监控</span>
        </div>
    </div>
    <div class="dashboard">
        <div class="video-container">
            <div class="video-wrapper">
                <video id="videoPlayer" class="video-player" controls>
                    您的浏览器不支持HTML5视频
                </video>
                <div class="speed-indicator" id="speedIndicator">1x</div>
                <div class="loading-overlay" id="videoLoadingOverlay" style="display:none;">
                    <div class="spinner"></div>
                    <p id="loadingText">正在加载录像...</p>
                </div>
            </div>

            <div class="video-controls">
                <button id="playBtn" class="control-btn btn-success" disabled>
                    <i class="fas fa-play"></i> 播放
                </button>
                <button id="pauseBtn" class="control-btn" disabled>
                    <i class="fas fa-pause"></i> 暂停
                </button>
                <button id="stopBtn" class="control-btn" disabled>
                    <i class="fas fa-stop"></i> 停止
                </button>
                <button id="speedDownBtn" class="control-btn" disabled>
                    <i class="fas fa-backward"></i> 减速
                </button>
                <button id="speedUpBtn" class="control-btn" disabled>
                    <i class="fas fa-forward"></i> 加速
                </button>
                <button id="snapshotBtn" class="control-btn" disabled>
                    <i class="fas fa-camera"></i> 截图
                </button>
                <button id="fullscreenBtn" class="control-btn">
                    <i class="fas fa-expand"></i> 全屏
                </button>
            </div>
        </div>

        <div class="panel">
            <h2 class="panel-title"><i class="fas fa-search"></i> 录像查询</h2>

            <div class="form-group">
                <label for="cameraSelect"><i class="fas fa-camera"></i> 选择摄像头</label>
                <select id="cameraSelect" class="form-control">
                    <option value="">-- 请选择摄像头 --</option>
                    <!-- 摄像头选项将通过JS动态生成 -->
                </select>
            </div>
            <div class="form-group">
                <label><i class="fas fa-history"></i> 历史回放设置</label>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                    <div style="width: 176px;">
                        <label>开始时间</label>
                        <input type="datetime-local" class="custom-datetime fa-calendar" id="startTime">
                    </div>
                    <div style="width: 176px;">
                        <label>结束时间</label>
                        <input type="datetime-local" class="custom-datetime" id="endTime">
                    </div>
                </div>
            </div>

            <button id="searchBtn" class="control-btn" style="width: 100%;">
                <i class="fas fa-search"></i> 查询录像
            </button>

            <div class="video-list" id="videoList">
                <div class="empty-state">
                    <i class="fas fa-info-circle"></i>
                    <p>请选择摄像头和时间范围查询录像</p>
                </div>
            </div>

            <div class="error-box" id="errorBox">
                <h3 class="error-title"><i class="fas fa-exclamation-triangle"></i> 查询错误</h3>
                <div class="error-message" id="errorMessage"></div>
                <button id="retryBtn" class="control-btn btn-danger" style="margin-top: 15px; width: 100%;">
                    <i class="fas fa-redo-alt"></i> 重试查询
                </button>
            </div>
        </div>
    </div>

    <footer>
        &copy; <span id="currentYear"></span> 视频监控系统 | 版本 1.0.0
    </footer>
</div>

<script src="{{ url_for('static', filename='js/flatpickr.min.js') }}"></script>
<script src="{{ url_for('static', filename='js/l10n/zh.js') }}"></script>
<script>
    // 录像播放器应用
    class VideoPlayerApp {
        constructor() {
            // DOM元素
            this.videoPlayer = document.getElementById('videoPlayer');
            this.playBtn = document.getElementById('playBtn');
            this.pauseBtn = document.getElementById('pauseBtn');
            this.stopBtn = document.getElementById('stopBtn');
            this.speedUpBtn = document.getElementById('speedUpBtn');
            this.speedDownBtn = document.getElementById('speedDownBtn');
            this.snapshotBtn = document.getElementById('snapshotBtn');
            this.fullscreenBtn = document.getElementById('fullscreenBtn');
            this.searchBtn = document.getElementById('searchBtn');
            this.cameraSelect = document.getElementById('cameraSelect');
            this.videoList = document.getElementById('videoList');
            this.errorBox = document.getElementById('errorBox');
            this.errorMessage = document.getElementById('errorMessage');
            this.retryBtn = document.getElementById('retryBtn');
            this.videoLoadingOverlay = document.getElementById('videoLoadingOverlay');
            this.loadingText = document.getElementById('loadingText');
            this.speedIndicator = document.getElementById('speedIndicator');

            // 状态变量
            this.currentPlaybackRate = 1.0;
            this.currentVideoList = [];
            this.isPlaying = false;
            this.currentVideoIndex = -1;

            this.loadCameras();
            this.setupEventListeners();
            this.updateFooterYear();
        }
        // 加载摄像头列表
        async loadCameras() {
            try {
                this.showLoading("正在加载摄像头列表...");

                const response = await fetch('/api/cameras');
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const data = await response.json();

                if (data.cameras && data.cameras.length > 0) {
                    this.cameraSelect.innerHTML = '<option value="">-- 请选择摄像头 --</option>' +
                            data.cameras.map(camera =>
                                `<option value="${camera.id}">${camera.name} (${camera.ip})</option>`
                            ).join('');
                } else {
                    this.cameraSelect.innerHTML = '<option value="">-- 没有可用的摄像头 --</option>';
                }

                this.hideLoading();
            } catch (error) {
                console.error('加载摄像头列表失败:', error);
                this.showError(`加载摄像头列表失败: ${error.message}`);
                this.hideLoading();
            }
        }

        // 设置事件监听器
        setupEventListeners() {
            // 视频播放器事件
            this.videoPlayer.addEventListener('play', () => {
                this.isPlaying = true;
                this.updateControlButtons();
                this.speedIndicator.style.display = 'block';
            });

            this.videoPlayer.addEventListener('pause', () => {
                this.isPlaying = false;
                this.updateControlButtons();
            });

            this.videoPlayer.addEventListener('ended', () => {
                this.playNextVideo();
            });

            this.videoPlayer.addEventListener('waiting', () => {
                this.showLoading("正在缓冲视频...");
            });

            this.videoPlayer.addEventListener('playing', () => {
                this.hideLoading();
            });

            this.videoPlayer.addEventListener('error', () => {
                this.showError("视频加载失败，请检查网络或文件路径");
                this.hideLoading();
            });

            // 播放控制按钮
            this.playBtn.addEventListener('click', () => this.playVideo());
            this.pauseBtn.addEventListener('click', () => this.pauseVideo());
            this.stopBtn.addEventListener('click', () => this.stopVideo());
            this.speedUpBtn.addEventListener('click', () => this.adjustSpeed(true));
            this.speedDownBtn.addEventListener('click', () => this.adjustSpeed(false));
            this.snapshotBtn.addEventListener('click', () => this.takeSnapshot());
            this.fullscreenBtn.addEventListener('click', () => this.toggleFullscreen());

            // 录像查询
            this.searchBtn.addEventListener('click', () => this.searchVideos());
            this.retryBtn.addEventListener('click', () => this.searchVideos());

            // 录像列表点击
            this.videoList.addEventListener('click', (e) => {
                const videoItem = e.target.closest('.video-item');
                if (videoItem) {
                    const index = parseInt(videoItem.dataset.index);
                    if (!isNaN(index)) {
                        this.playSelectedVideo(index);
                    }
                }
            });

            // 键盘快捷键
            document.addEventListener('keydown', (e) => {
                if (e.target.tagName === 'INPUT' || e.target.tagName === 'SELECT') return;

                switch (e.key) {
                    case ' ':
                        // 空格键切换播放/暂停
                        e.preventDefault();
                        if (this.isPlaying) {
                            this.pauseVideo();
                        } else {
                            this.playVideo();
                        }
                        break;
                    case 'ArrowRight':
                        // 右箭头加速
                        e.preventDefault();
                        this.adjustSpeed(true);
                        break;
                    case 'ArrowLeft':
                        // 左箭头减速
                        e.preventDefault();
                        this.adjustSpeed(false);
                        break;
                    case 'f':
                        // F键全屏
                        e.preventDefault();
                        this.toggleFullscreen();
                        break;
                    case 'n':
                        // N键下一个视频
                        e.preventDefault();
                        this.playNextVideo();
                        break;
                }
            });
        }

        // 更新控制按钮状态
        updateControlButtons() {
            this.playBtn.disabled = !this.videoPlayer.src || this.isPlaying;
            this.pauseBtn.disabled = !this.videoPlayer.src || !this.isPlaying;
            this.stopBtn.disabled = !this.videoPlayer.src;
            this.snapshotBtn.disabled = !this.videoPlayer.src;

            // 更新速度按钮状态
            this.speedUpBtn.disabled = this.currentPlaybackRate >= 16;
            this.speedDownBtn.disabled = this.currentPlaybackRate <= 0.25;

            // 更新速度指示器
            this.speedIndicator.textContent = `${this.currentPlaybackRate}x`;
        }

        // 播放视频
        playVideo() {
            if (this.videoPlayer.src) {
                this.videoPlayer.play().catch(error => {
                    console.error('播放失败:', error);
                    this.showError(`播放失败: ${error.message}`);
                });
            }
        }

        // 暂停视频
        pauseVideo() {
            this.videoPlayer.pause();
        }

        // 停止视频
        stopVideo() {
            this.videoPlayer.pause();
            this.videoPlayer.currentTime = 0;
            this.isPlaying = false;
            this.updateControlButtons();
            this.speedIndicator.style.display = 'none';
        }

        // 调整播放速度
        adjustSpeed(increase) {
            if (increase) {
                if (this.currentPlaybackRate < 16) {
                    this.currentPlaybackRate *= 2;
                }
            } else {
                if (this.currentPlaybackRate > 0.25) {
                    this.currentPlaybackRate /= 2;
                }
            }

            this.videoPlayer.playbackRate = this.currentPlaybackRate;
            this.updateControlButtons();
        }

        // 截图
        takeSnapshot() {
            if (this.videoPlayer.readyState === 0) return;

            const canvas = document.createElement('canvas');
            canvas.width = this.videoPlayer.videoWidth;
            canvas.height = this.videoPlayer.videoHeight;

            const ctx = canvas.getContext('2d');
            ctx.drawImage(this.videoPlayer, 0, 0, canvas.width, canvas.height);

            const link = document.createElement('a');
            const timestamp = new Date().toISOString().slice(0, 19).replace(/:/g, '-');
            const filename = `snapshot-${timestamp}.png`;

            link.download = filename;
            link.href = canvas.toDataURL('image/png');
            link.click();

            // 显示截图成功提示
            this.showTempMessage(`截图已保存: ${filename}`);
        }

        // 切换全屏
        toggleFullscreen() {
            if (!document.fullscreenElement) {
                this.videoPlayer.requestFullscreen().catch(err => {
                    console.error('全屏错误:', err);
                    this.showError(`无法进入全屏模式: ${err.message}`);
                });
            } else {
                document.exitFullscreen();
            }
        }

        // 查询录像
        async searchVideos() {
            this.videoList.innerHTML = '';
            const cameraId = this.cameraSelect.value;
            let startTime = document.getElementById('startTime').value;
            let endTime = document.getElementById('endTime').value;

            // 验证输入
            if (!cameraId) {
                this.showError('请选择摄像头');
                return;
            }

            if (!startTime || !endTime) {
                this.showError('请选择完整的时间范围');
                return;
            }

            // 检查时间范围是否合理
            const start = new Date(startTime).getTime();
            const end = new Date(endTime).getTime();

            if (start >= end) {
                this.showError('结束时间必须晚于开始时间');
                return;
            }

            if (end - start > 30 * 24 * 60 * 60 * 1000) {
                this.showError('时间范围不能超过30天');
                return;
            }

            // 显示加载状态
            this.showLoading("正在查询录像...");
            this.errorBox.style.display = 'none';
            this.videoPlayer.src = '';
            this.currentVideoList = [];
            this.currentVideoIndex = -1;
            this.updateControlButtons();

            try {
                const response = await fetch(`/api/videos?camera_id=${cameraId}&start_time=${encodeURIComponent(startTime)}&end_time=${encodeURIComponent(endTime)}`);

                if (!response.ok) {
                    const errorData = await response.json().catch(() => ({}));
                    throw new Error(errorData.error || `HTTP错误! 状态码: ${response.status}`);
                }

                const data = await response.json();

                if (!data.videos || data.videos.length === 0) {
                    throw new Error('没有找到指定时间段的录像');
                }

                this.currentVideoList = data.videos;
                this.renderVideoList(data.videos);
                this.hideLoading();

                // 自动播放第一个视频
                if (data.videos.length > 0) {
                    this.playSelectedVideo(0);
                }
                this.errorBox.style.display = 'none';
            } catch (error) {
                console.error('查询录像失败:', error);
                this.showError(error.message);
                this.hideLoading();
            }
        }

        // 渲染录像列表
        renderVideoList(videos) {
            this.videoList.innerHTML = '';

            if (!videos || videos.length === 0) {
                this.videoList.innerHTML = `
                    <div class="empty-state">
                        <i class="fas fa-info-circle"></i>
                        <p>没有找到录像文件</p>
                    </div>
                `;
                return;
            }

            const fragment = document.createDocumentFragment();

            videos.forEach((video, index) => {
                const videoItem = document.createElement('div');
                videoItem.className = 'video-item';
                videoItem.dataset.index = index;

                if (index === this.currentVideoIndex) {
                    videoItem.classList.add('active');
                }

                videoItem.innerHTML = `
                    <div class="video-item-title">
                        <i class="fas fa-video"></i>
                        ${video.filename}
                    </div>
                    <div class="video-item-info">
                        <span><i class="fas fa-clock"></i> ${video.time}</span>
                        <span><i class="fas fa-file"></i> ${this.formatFileSize(video.size)}</span>
                    </div>
                `;

                fragment.appendChild(videoItem);
            });

            this.videoList.appendChild(fragment);
        }

        // 播放选中的录像
        playSelectedVideo(index) {
            if (index < 0 || index >= this.currentVideoList.length) return;

            this.currentVideoIndex = index;
            const video = this.currentVideoList[index];

            // 更新选中状态
            this.renderVideoList(this.currentVideoList);

            // 显示加载状态
            this.showLoading("正在加载录像...");
            this.videoPlayer.src = '';

            // 设置视频源
            const videoSrc = `/static/videos/${video.filename}`;
            this.videoPlayer.src = videoSrc;
            this.videoPlayer.load();

            // 重置播放速度
            this.currentPlaybackRate = 1.0;
            this.videoPlayer.playbackRate = this.currentPlaybackRate;
            this.updateControlButtons();

            // 处理加载完成或错误
            this.videoPlayer.oncanplay = () => {
                this.hideLoading();
                this.videoPlayer.play().catch(error => {
                    console.error('自动播放失败:', error);
                    this.showError(`自动播放失败: ${error.message}`);
                });
                this.videoPlayer.oncanplay = null;
            };

            this.videoPlayer.onerror = () => {
                this.hideLoading();
                this.showError("视频加载失败，请检查文件是否存在");
                this.videoPlayer.onerror = null;
            };
        }

        // 播放下一个视频
        playNextVideo() {
            if (this.currentVideoList.length === 0) return;

            const nextIndex = (this.currentVideoIndex + 1) % this.currentVideoList.length;
            this.playSelectedVideo(nextIndex);
        }

        // 显示加载状态
        showLoading(message) {
            this.loadingText.textContent = message || "正在加载...";
            this.videoLoadingOverlay.style.display = 'flex';
        }

        // 隐藏加载状态
        hideLoading() {
            this.videoLoadingOverlay.style.display = 'none';
        }

        // 显示错误信息
        showError(message) {
            this.errorMessage.textContent = message;
            this.errorBox.style.display = 'block';
        }

        // 显示临时消息
        showTempMessage(message, duration = 3000) {
            const tempMsg = document.createElement('div');
            tempMsg.className = 'temp-message';
            tempMsg.textContent = message;

            // 样式
            tempMsg.style.position = 'fixed';
            tempMsg.style.bottom = '20px';
            tempMsg.style.left = '50%';
            tempMsg.style.transform = 'translateX(-50%)';
            tempMsg.style.backgroundColor = 'rgba(0, 0, 0, 0.8)';
            tempMsg.style.color = 'white';
            tempMsg.style.padding = '10px 20px';
            tempMsg.style.borderRadius = '5px';
            tempMsg.style.zIndex = '1000';
            tempMsg.style.transition = 'opacity 0.5s';

            document.body.appendChild(tempMsg);

            // 自动消失
            setTimeout(() => {
                tempMsg.style.opacity = '0';
                setTimeout(() => tempMsg.remove(), 500);
            }, duration);
        }

        // 格式化文件大小
        formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // 更新页脚年份
        updateFooterYear() {
            document.getElementById('currentYear').textContent = new Date().getFullYear();
        }
    }

    // 初始化应用
    document.addEventListener('DOMContentLoaded', () => {
        new VideoPlayerApp();

        // 初始化日期时间选择器
        if (typeof flatpickr === "undefined") {
            console.error("Flatpickr未正确加载！");
            return;
        }

        const yesterday = new Date();
        yesterday.setHours(yesterday.getHours() - 1);

        flatpickr("#startTime", {
            dateFormat: "Y-m-d H:i",
            defaultDate: yesterday,
            position: "auto",
            enableTime: true,
            maxDate: new Date(),
            minuteIncrement: 1,
            disableMobile: true,
            time_24hr: true
        });
        flatpickr("#endTime", {
            dateFormat: "Y-m-d H:i",
            defaultDate: new Date(),
            position: "auto",
            enableTime: true,
            maxDate: new Date(),
            minuteIncrement: 1,
            disableMobile: true,
            time_24hr: true
        });
    });
</script>
</body>
</html>